package com.dk.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.dk.data.Result;

import com.dk.domain.TSpikeDTO;
import com.dk.em.ConstantEnum;
import com.dk.pojo.TSpike;
import com.dk.service.ITSpikeService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("tSpikeAddController")
public class TSpikeAddController {

    @Autowired
    private ITSpikeService itSpikeService;


    @ApiOperation(value = "秒杀查询")
    @GetMapping
    public Result getInfoIdBy(){
        List<TSpike> list = itSpikeService.getInfoAll();
        //数据传输转换
        List<TSpikeDTO> dtoList = JSONObject.parseArray(JSONObject.toJSONString(list), TSpikeDTO.class);
        return Result.bulid(ConstantEnum.SUCCESS).setResult(dtoList);
    }

    @ApiOperation(value = "秒殺增加操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId",value = "商品的ID",required = true,paramType = "query"),
            @ApiImplicitParam(name = "title",value = "标题",required = true,paramType = "query"),
            @ApiImplicitParam(name = "price",value = "原价格",required = true,paramType = "query"),
            @ApiImplicitParam(name = "sellerId",value = "商家id",required = true,paramType = "query"),
            @ApiImplicitParam(name = "startTime",value = "开始时间",required = true,paramType = "query"),
            @ApiImplicitParam(name = "endTime",value = "结束时间",required = true,paramType = "query"),
            @ApiImplicitParam(name = "stockCount",value = "剩余库存数",required = true,paramType = "query"),

    })
    @PostMapping(value = "/add",headers="content-type=multipart/form-data")
    public Result add(TSpike tSpike,
                      @ApiParam(name="myFile",value = "用户图片",required = true)MultipartFile myFile){
        String imgUrl = upload(myFile);
        tSpike.setDeleted(0);
        tSpike.setVersion(1);
        tSpike.setStatus(0);
        tSpike.setCheckTime(new Date());
        tSpike.setCreateTime(new Date());
        tSpike.setUpdateTime(new Date());
        tSpike.setSmallPic(imgUrl);
        boolean b = itSpikeService.save(tSpike);
        if(b){
            return Result.bulid(ConstantEnum.SUCCESS);
        }
        return Result.bulid(ConstantEnum.ERROR);
    }

    //上传图片
    public String upload(MultipartFile image){
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String http = "http://";
        String bucketName = "dongdongshop-lidongdong";
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tA9N9TMawsjei1CMDvi";
        String accessKeySecret = "NwQtbULuN0LymC9JDeNQJ0uKkKm0kN";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 填写字符串。
        // String content = "Hello OSS";
        //把文件变成流
        InputStream inputStream = null;
        try {
            inputStream = image.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String originalFilename = image.getOriginalFilename();

        // 创建PutObjectRequest对象。
        // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, originalFilename,inputStream);

        // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传字符串。
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();
        return http + bucketName + "." + endpoint + "/" + originalFilename;
    }

    @ApiOperation(value = "车辆信息修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tSpike",value = "实体类:秒杀表",required = true,paramType = "body",dataTypeClass = TSpike.class)
    })
    @PutMapping(value = "/update")
    public Result getInfoIdup(@RequestBody TSpike tSpike){

        Integer i = itSpikeService.updateInfo(tSpike);
        if(i>0){
            return Result.bulid(ConstantEnum.SUCCESS);
        }
        return Result.bulid(ConstantEnum.ERROR);
    }

    @ApiOperation(value = "秒杀信息逻辑删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "path"),
            @ApiImplicitParam(name = "status",value = "状态",required = true,paramType = "path")
    })
    @PutMapping(value = "/{status},{id}")
    public Result deleStatus(@PathVariable("id") Integer id,@PathVariable("status")Integer status){

        TSpike byId = itSpikeService.getById(id);
        byId.setStatus(status);
        boolean b = itSpikeService.updateById(byId);
        if(b){
            return Result.bulid(ConstantEnum.SUCCESS);
        }
        return Result.bulid(ConstantEnum.ERROR);
    }
}
